package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.support.AdminResponseUtils;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.type.AdminTypeEnum;
import com.qiguliuxing.dts.common.util.RegexUtils;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.common.util.bcrypt.BCryptPasswordEncoder;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsAdmin;
import com.qiguliuxing.dts.service.base.DtsAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.qiguliuxing.dts.admin.support.AdminResponseCode.*;

@RestController
@RequestMapping("/admin/admin")
@Validated
@Api(tags = ApiAdminConsts.Admin.PARENT)
public class AdminAdminController {
	private static final Logger logger = LoggerFactory.getLogger(AdminAdminController.class);

	@Autowired
	private DtsAdminService adminService;

	@GetMapping("/list")
	@RequiresPermissions("admin:admin:list")
	@RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Admin.LIST)
	@WebLog(description = ApiAdminConsts.Admin.LIST,  excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "用户名称") String username,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsAdmin> adminList = adminService.querySelective(username, page, limit, sort, order);
		long total = PageInfo.of(adminList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", adminList);
		return ResponseUtils.ok(data);
	}

	private Object validate(DtsAdmin admin) {
		String name = admin.getUsername();
		if (StringUtils.isEmpty(name)) {
			return ResponseUtils.badArgument();
		}
		if (!RegexUtils.isUsername(name)) {
			logger.error("校验错误：{}", ADMIN_INVALID_NAME.desc());
			return AdminResponseUtils.fail(ADMIN_INVALID_NAME);
		}
		String password = admin.getPassword();
		if (StringUtils.isEmpty(password) || password.length() < 6) {
			logger.error("校验错误：{}", ADMIN_INVALID_PASSWORD.desc());
			return AdminResponseUtils.fail(ADMIN_INVALID_PASSWORD);
		}
		String mail = admin.getMail();
		if (StringUtils.isEmpty(mail)) {
			logger.error("校验错误：{}", ADMIN_INVALID_MAIL.desc());
			return AdminResponseUtils.fail(ADMIN_INVALID_MAIL);
		}
		String tel = admin.getTel();
		if (!RegexUtils.isMobileExact(tel)) {
			logger.error("校验错误:{}", ADMIN_INVALID_MOBILE.desc());
			return AdminResponseUtils.fail(ADMIN_INVALID_MOBILE);
		}
		return null;
	}

	@PostMapping("/create")
	@RequiresPermissions("admin:admin:create")
	@RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "添加")
	@ApiOperation(value = ApiAdminConsts.Admin.CREATE)
	@WebLog(description = ApiAdminConsts.Admin.CREATE,  persistence = true)
	public Object create(@RequestBody DtsAdmin admin) {
		Object error = validate(admin);
		if (error != null) {
			return error;
		}

		String username = admin.getUsername();
		List<DtsAdmin> adminList = adminService.findAdmin(username);
		if (adminList.size() > 0) {
			logger.error("系统管理->管理员管理->添加 ,错误：{}", ADMIN_NAME_EXIST.desc());
			return AdminResponseUtils.fail(ADMIN_NAME_EXIST);
		}

		String rawPassword = admin.getPassword();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encodedPassword = encoder.encode(rawPassword);
		admin.setPassword(encodedPassword);

		// 创建的用户为管理后台的用户
		admin.setType(AdminTypeEnum.ADMIN.getType());
		adminService.add(admin);

		return ResponseUtils.ok(admin);
	}

	@GetMapping("/read")
	@RequiresPermissions("admin:admin:read")
	@RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "详情")
	@ApiOperation(value = ApiAdminConsts.Admin.READ)
	@WebLog(description = ApiAdminConsts.Admin.READ)
	public Object read(@ApiParam(value = "管理员id") @NotNull Integer id) {
		DtsAdmin admin = adminService.findById(id);
		return ResponseUtils.ok(admin);
	}

	@PostMapping("/update")
	@RequiresPermissions("admin:admin:update")
	@RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "编辑")
	@ApiOperation(value = ApiAdminConsts.Admin.UPDATE)
	@WebLog(description = ApiAdminConsts.Admin.UPDATE,  persistence = true)
	public Object update(@RequestBody DtsAdmin admin) {
		Object error = validate(admin);
		if (error != null) {
			return error;
		}

		Integer anotherAdminId = admin.getId();
		if (anotherAdminId == null) {
			return ResponseUtils.badArgument();
		}

		String rawPassword = admin.getPassword();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String encodedPassword = encoder.encode(rawPassword);
		admin.setPassword(encodedPassword);

		if (adminService.updateById(admin) == 0) {
			logger.error("系统管理->管理员管理-编辑 ,错误：{}", "更新数据失败！");
			return ResponseUtils.updatedDataFailed();
		}

		return ResponseUtils.ok(admin);
	}

	@PostMapping("/delete")
	@RequiresPermissions("admin:admin:delete")
	@RequiresPermissionsDesc(menu = { "系统管理", "管理员管理" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Admin.DELETE)
	@WebLog(description = ApiAdminConsts.Admin.DELETE,  persistence = true)
	public Object delete(@RequestBody DtsAdmin admin) {
		Integer anotherAdminId = admin.getId();
		if (anotherAdminId == null) {
			return ResponseUtils.badArgument();
		}

		adminService.deleteById(anotherAdminId);
		return ResponseUtils.ok();
	}
}
